import React from "react";
import {connect} from "react-redux";
import {NavBar, Icon, List, InputItem} from "antd-mobile";
import {getMsgList, sendMsg, recMsg, readMsg} from "../../redux/chatMsg.redux";
import {getChatId} from "../../utils";

@connect(
  state => state,
  {getMsgList, sendMsg, recMsg, readMsg}
)
class Chat extends React.Component {
  constructor () {
    super();
    this.state = {
      text: ""
    };

    this.sendMsg = this.sendMsg.bind(this);
  }

  componentDidMount () {
    if (!this.props.chatMsg.chatMsgList || !this.props.chatMsg.chatMsgList.length) {
      this.props.getMsgList();
      this.props.recMsg();
    }
  }

  componentWillUnmount () {
    const from = this.props.match.params.userId;
    this.props.readMsg(from);
  }

  sendMsg () {
    const from = this.props.user._id;
    const to = this.props.match.params.userId;
    this.props.sendMsg({from, to, content: this.state.text});
    this.setState({text: ''});
  }

  render () {
    const me = this.props.user._id;
    const userId = this.props.match.params.userId;
    const chatId = getChatId(me, userId);
    const msgList = this.props.chatMsg.chatMsgList.filter(m => m.chatId === chatId);
    const users = this.props.chatMsg.users;
    const username = users[userId].username;
    const avatar = users[userId].avatar;
    const imgSrc = require(`./avatar/${avatar}.png`);
    const meSrc = require(`./avatar/${this.props.user.avatar}.png`);
    const Item = List.Item;
    return (
      <div>
        <NavBar
          icon={<Icon type="left"/>}
          onLeftClick={() => this.props.history.goBack()}>
          {username}
        </NavBar>
        {/*聊天记录*/}
        {
          users[userId] ?
            msgList.map(v => {
              return v.from !== me ? (
                <List key={v._id}>
                  <Item thumb={imgSrc}>
                    {v.content}
                  </Item>
                </List>
              ) : (
                <List className="chat-me" key={v._id}>
                  <Item extra={<img src={meSrc} alt="头像"/>}>
                    {v.content}
                  </Item>
                </List>
              )
            })
            : null
        }
        {/*底部输入*/}
        <div className="stick-footer">
          <List>
            <InputItem placeholder="请输入" value={this.state.text}
                       onChange={v => this.setState({'text': v})}
                       extra={<span onClick={this.sendMsg}>发送</span>}/>
          </List>
        </div>
      </div>
    );
  }
}

export default Chat;